﻿using Bigway.Common.Jobs;
using Bigway.Common.Models.DtoModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using static System.Threading.Tasks.Task;

namespace Bigway.Common.Controllers;
using static Errors;

[ApiController]
[Route("api/jobqueue")]
public class JobQueueController(JobRegistryProvider jobRegistryProvider, ILogger<JobQueueController> logger): ControllerBase
{
    private readonly BaseJobRegistry _jobRegistry = jobRegistryProvider.JobRegisty;

    [HttpPost]
    public NoDataResponseDto AddJobToQueue(
        [FromQuery(Name = "api_key")] string apiKey,
        [FromBody] TriggerJobRequestDto request,
        CancellationToken token = default
        )
    {
        var jobId = IBackgroundJob.GetJobId(request.SystemId, request.JobName);
        logger.LogInformation("Queuing job {JobId}...", jobId);
        var jobInfo = _jobRegistry.GetJobInfo(jobId);
        if (jobInfo is null)
        {
            logger.LogWarning("The job {JobId} is not found", jobId);
            return BackgroundJobNotFound<NoDataResponseDto>(jobId);
        }

        Run(async () =>
        {
            // ReSharper disable once MethodSupportsCancellation
            await jobInfo.ScheduleToRunImmediatelyWithDefaultDelayAsync();
        }, token);
        return new NoDataResponseDto();
    }
}